home *** CD-ROM | disk | FTP | other *** search
- Path: news.lpr.carel.fi!usenet
- From: Ari Lukumies <aril@cmt.lpr.mail.carel.fi>
- Newsgroups: comp.lang.c
- Subject: Re: read/write integers to files
- Date: Thu, 07 Mar 1996 16:48:28 +0200
- Organization: Carelcomp Forest
- Message-ID: <313EF73C.3B54@cmt.lpr.mail.carel.fi>
- References: <313EBF65.4E82@www.inia.net.au>
- NNTP-Posting-Host: renoir.cclahti.carel.fi
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (WinNT; I)
-
- Jason Collins wrote:
- >
- > Hi there,
- >
- > I would preface this question with the standard "dumb newbie question......." or whatever but I
- > think you'll work it out for yourselves soon enough.
- >
- > My problem is that I'm trying to write a program that will read an integer from the file
- > count.dat, increment the integer then write it back to count.dat. I have provided the listing so
- > that you can all tell me what I'm doing wrong.
- >
- > Thanks....and.....be gentle.
- >
- > --------------------
- > counter.c
- > --------------------
- >
- > #include <stdio.h>
- > #include <stdlib.h>
- >
- > FILE *filePtr;
- >
- > void main()
- > {
- > char ctr;
- >
- > filePtr=fopen("count.dat", "ab");
- > fscanf(filePtr, "%d", &ctr);
- > fclose(filePtr);
- >
- > ctr++;
- >
- > filePtr=fopen("count.dat", "wb");
- > fprintf(filePtr, "%d", ctr);
- > fclose(filePtr);
- > }
-
- Reading an integer? Why not declare it so, then:
-
- int ctr;
-
- And, if you don't plan to append data to the end of the file, why open it in append
- mode? You could use just "rb" instead.
-
- The second fopen in "wb" mode still will truncate the file to zero-length if it
- exists. You could try "rb+" (open in read binary mode with ability to write also):
-
- filePtr = fopen("count.dat", "rb+");
- fscanf(filePtr, "%d", &ctr);
- ctr++;
- rewind(filePtr);
- fprintf(filePtr, "%d", ctr);
- fclose(filePtr);
-
- However, I'd stick Xscanf to where it belongs and use fread/fwrite instead, when
- dealing with binary data. Fseek is also an useful function.
-
- Also, checking for failures in fopen etc is a good programming practice.
-
- Later,
- AriL
- --
- All my opinions are mine and mine alone.
-